package org.ee.framework.jpa.base;

import jakarta.persistence.*;
import org.hibernate.annotations.Comment;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.domain.Persistable;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

/**
 * 基础实体
 */
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class AbstractEntity<ID> implements Persistable<ID> {
    @Transient
    private boolean isNew = true;

    @Override
    public boolean isNew() {
        return isNew;
    }

    @PostPersist
    @PostLoad
    void markNotNew() {
        this.isNew = false;
    }

    @Comment("创建用户")
    @CreatedBy
    private String createdUser;
    @Comment("更新用户")
    @LastModifiedBy
    private String updatedUser;
    @Comment("创建时间")
    @CreatedDate
    private LocalDateTime createdTime;
    @Comment("更新时间")
    @LastModifiedDate
    private LocalDateTime updatedTime;

    @PrePersist
    public void prePersist() {
        if (this.createdTime == null) {
            this.createdTime = LocalDateTime.now();
        }
        if (this.createdUser == null) {
            this.createdUser = "defaultUser"; // 你可以从安全上下文或请求中获取当前用户
        }
    }

    @PreUpdate
    public void preUpdate() {
        this.updatedTime =LocalDateTime.now();  // 自动填充更新时间
        this.updatedUser = "defaultUser";  // 你可以从安全上下文或请求中获取当前用户
    }

    // 抽象方法 getId 由子类实现
    @Override
    public abstract ID getId();

    public String getCreatedUser() {
        return createdUser;
    }

    public void setCreatedUser(String createdUser) {
        this.createdUser = createdUser;
    }

    public String getUpdatedUser() {
        return updatedUser;
    }

    public void setUpdatedUser(String updatedUser) {
        this.updatedUser = updatedUser;
    }

    public LocalDateTime getUpdatedTime() {
        return updatedTime;
    }

    public void setUpdatedTime(LocalDateTime updatedTime) {
        this.updatedTime = updatedTime;
    }

    public LocalDateTime getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(LocalDateTime createdTime) {
        this.createdTime = createdTime;
    }

    public void setNew(boolean aNew) {
        isNew = aNew;
    }
}
